<?php
use Phalcon\Mvc\Controller;

class SqlController extends Controller {

    private $className;

    public function initialize() {
        $this->className = "demo";
    }

    public function setClassName($className) {
        $this->className = $className;

        return $this;
    }

    public function checkStringAction($text) {
        if($this->checkString($text)) {
            echo "clear";
        }else {
            echo "risk";
        }
    }

    public function checkIntAction($integer) {
        if($this->checkInt($integer)) {
            echo "clear";
        }else {
            echo "risk";
        }
    }

    public function checkInt($integer, $func = "") {
        if(is_numeric($integer)) {
            return true;
        }else {
            $this->logger($text, $func);
            return false;
        }
    }

    public function checkString($text, $func = "") {
        $state = 0;

        $list = explode(" ", $text);

        foreach($list as $word) {
            $l = explode(";", $word);

            foreach($l as $w) {
                switch($state) {
                    case 0:
                        if($this->quote_check($w)) {
                            $state = 1;
                        }
                        break;
                    case 1:
                        if($this->sql_keyword_check($w)) {
                            if($state == 1) {
                                $state = 2;
                            }
                        }else if($this->quote_check($w)) {
                            $state = 0;
                        }
                        break;
                    case 2:
                        $this->logger($text, $func);
                        return false;
                }
            }
        }
        return true;
    }

    private function sql_keyword_check($sql_str) {
        return preg_match('/select|insert|and|or|update|delete|union|into|load_file|outfile/i', $sql_str);
        //return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
    }

    private function quote_check($str) {
        return preg_match('/\'/i', $str);
    }

    private function logger($text, $func) {
        $the_date = date('Y-m-d H:i:s');
        $file = fopen("logger.txt", "a");

        fwrite($file, "[Warning]"." ".$this->className.":".$func."  [".$the_date."]    ".$text."\n");

        fclose($file);
    }
}
